<!-- Modal -->
<div class="modal" id="modal-pwd" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 id="modal-pwd-title" class="modal-title">Modal title</h5>
            </div>
            <div class="modal-body">
                <div id="modal-pwd-text">Modal Text</div>
                <br>
                <div><b>Key length must be 8/16/32 !</b></div>
                <br>
                <div class="input-group">
                    <div class="input-group-prepend">
                        <div class="input-group-text"><i class="material-icons-sm">lock</i></div>
                    </div>
                    <input id="modal-pwd-input" type="text" class="form-control">
                </div>
                <div id="modal-pwd-error" class="text-danger"></div>
            </div>
            <div class="modal-footer">
                <button id="btn-setpwd" type="button" class="btn btn-primary">Confirm</button>
            </div>
        </div>
    </div>
</div>

<script>
    // 检查解锁状态
    $(document).ready(function () {
        if (!isLogin()) {
            $("#modal-pwd-title").text("Please enter your password to unlock.");
            $("#modal-pwd-text").text("Enter a key to encrypt or decrypt your data, " +
                "we never storage any raw data on our server, " +
                "please remember your key and you will lost all the data if you forgot it.");

            $("#modal-pwd").modal({
                backdrop: true
            });
        }
    });

    // 验证key格式是否正确，此处不会验证key的正确与否
    $("#btn-setpwd").click(function () {
        let pwd = $("#modal-pwd-input").val();
        if (pwd.length == 0 || pwd.length % 8 != 0 || pwd.length > 32) {
            $("#modal-pwd-error").text("key length must be 8/16/32, your key's length is " + pwd.length + ".");
            return;
        }
        set_pwd(pwd);
        $("#modal-pwd").modal("hide");
        $("#btn-add").removeAttr("hidden");
        $("#btn-unlock").attr("hidden", 'hidden');
        // 刷新页面才能解密数据
        location.reload();
    });

    // 重新输入key的时候清除错误信息
    $("#modal-pwd-input").click(function () {
        $("#modal-pwd-error").text("");
    });
</script>